package com.wuxiaofan.service;

import cn.hutool.crypto.SecureUtil;
import com.wuxiaofan.entity.User;
import com.wuxiaofan.mapper.UserMapper;
import com.wuxiaofan.vo.ReturnResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public ReturnResult login(User user, HttpServletRequest request, HttpServletResponse response) {
        User userTmp = userMapper.findByPhoneNumber(user.getPhoneNumber());
        if (userTmp == null) {
            return ReturnResult.failure("用户名不存在!");
        }
        if (!userTmp.getPassword().equals(encodePasswd(user.getPassword(), userTmp.getSlat()))) {
            return ReturnResult.failure("密码错误!");
        }
        String ticket = UUID.randomUUID().toString().replace("-", "");
        request.getSession().setAttribute(ticket, userTmp);
        Cookie cookie = new Cookie("ticket", ticket);
        response.addCookie(cookie);
        return ReturnResult.success("登录成功!", userTmp.getId());
    }

    public void addUser(User user) {
        String slat = UUID.randomUUID().toString().replace("-", "");
        user.setPassword(encodePasswd(user.getPassword(), slat));
        user.setSlat(slat);
        user.setHead("-");
        userMapper.insert(user);
    }

    //md5(md5(pass明文+salt)+salt)
    private String encodePasswd(String passwd, String slat) {
        return SecureUtil.md5(SecureUtil.md5(passwd + slat) + slat);
    }
}
